package com.example.mytestdemo.utils

import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.example.mytestdemo.utils.KeyboardUtils

/**
 * @author tgw
 * @date 2022/7/4
 * @describe
 */
object KeyboardUtils {
    /**
     * 显示键盘
     */
    fun showKeyboard(view: View) {
        val imm = getInputMethodManager(view.context)
        if (imm != null) {
            view.requestFocus()
            imm.showSoftInput(view, 0)
        }
    }

    /**
     * 隐藏键盘
     */
    fun hideKeyboard(view: View) {
        val imm = getInputMethodManager(view.context)
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    /**
     * 切换键盘的弹出和隐藏
     */
    fun toggleSoftInput(view: View) {
        val imm = getInputMethodManager(view.context)
        if (imm != null) {
            imm.toggleSoftInput(0, 0)
        }
    }

    /**
     * 强制显示键盘
     *
     * @param context
     * @param view
     */
    fun show(context: Context, view: View?) {
        val imm = getInputMethodManager(context)
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED)
    }

    /**
     * 强制隐藏键盘
     *
     * @param context
     * @param view
     */
    fun hide(context: Context, view: View?) {
        val imm = getInputMethodManager(context)
        if (imm.isActive) {
            if (view != null && view.windowToken != null) {
                imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
    }

    /**
     * 输入法是否打开
     *
     * @param context
     * @return true，则表示输入法打开
     */
    fun isShow(context: Context): Boolean {
        val imm = getInputMethodManager(context)
        return imm.isActive
    }

    /**
     * 获取 InputMethodManager
     * @param context
     * @return
     */
    fun getInputMethodManager(context: Context): InputMethodManager {
        return context.applicationContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    }
}